<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Помощник-виджет для отрисовки меню в виде дерева (с использование< JavaScript)
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */

/**
 * Отрисовка виджета
 * 
 * @access public
 * @param string $str
 * @return string
 */
function xtree_menu_widget($params = array()) {
   $obj =& get_instance();
   $obj->load->language('tree');
   
   // Получаем идентификатор меню
   $name = $params['name'];
   $obj->benchmark->mark('process_xtree_menu_(_' . $name . '_)_start');
   $id_menu = 0;
   $obj->load->model('m_table');
   $obj->m_table->set_table('menus');
   $obj->m_table->add_restriction('name', $name);
   $obj->m_table->load_results();
   if (0 < $obj->m_table->get_count()) {
      $result = $obj->m_table->next_result();
      $id_menu = $result['id_menu'];
   }
   // Получаем идентификатор текущего элемента меню
   $id_content = null;
   if (isset($params['id'])) {
      $id_content = (int) $params['id'];
   }
   if (0 == $id_content) {
      $id_content = null;
   }
   
   // Подгружеам все дерево контентов
   $obj->load->helper('tree');
   $obj->m_table->set_table('contents');
   $obj->m_table->add_restriction('id_menu', $id_menu);
   $obj->m_table->add_restriction('status', 'active'); 
   $obj->m_table->add_sort('position');
   $obj->m_table->load_results();
   $contents = $obj->m_table->get_results();
   $tree = array_tree($contents, 'id_content', 'id_parent');
   
   $obj->load->helper('content');
   $data = array(
      'tree' => tree_html($tree),
      'id_content' => (string) (int) $id_content
   );
   $output = $obj->parser->parse('widgets/xtree_menu/' . $name . '.html', $data, true);
   $obj->benchmark->mark('process_xtree_menu_(_' . $name . '_)_end');
   return $output;
} // end xtree_menu_widget

/**
 * Создание HTML по дереву
 *
 * @param array $tree
 * @return string
 */
function tree_html(&$tree) {
   $obj =& get_instance();
   $output = $obj->lang->line('tree_parent_open');
   foreach ($tree as $branch) {
      $output .= $obj->lang->line('tree_item_open');
      $output .= str_replace(array('{%link%}', '{%title%}', '{%id_content%}'), array(get_url($branch), $branch['title'], $branch['id_content']), $obj->lang->line('tree_item'));
      if (isset($branch['child']) && is_array($branch['child']) && 0 < count($branch['child'])) {
         $output .= tree_html($branch['child']);
      }
      $output .= $obj->lang->line('tree_item_close');
   }
   $output .= $obj->lang->line('tree_parent_close');
   return $output;
} // end tree_html
